package main

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	setGetRoute(r)
	setPostRoute(r)

	err := r.Run()
	if err != nil {
		panic(err)
	}
}

// setGetRoute GET请求路由
func setGetRoute(r *gin.Engine) {
	// 参数作为URL路径传递 localhost:8080/hello/1
	r.GET("/hello/:id", func(c *gin.Context) {
		id := c.Param("id")
		fmt.Println("Param id:", id) // Param id: 1
	})

	// 参数作为URL参数传递 localhost:8080/hello?id=1
	r.GET("/hello", func(c *gin.Context) {
		id := c.Query("id")
		fmt.Println("Query id:", id) // Query id: 1
	})
	// 多个参数 localhost:8080/hi?id=1&name=lena
	r.GET("/hi", func(c *gin.Context) {
		id := c.Query("id")
		name := c.Query("name")
		fmt.Println("Query :", id, name) // Query : 1 lena
	})
}

type student struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
	Age  int    `json:"age"`
}

// setPostRoute 设置post请求
func setPostRoute(r *gin.Engine) {
	// 请求值绑定到结构体 curl --location --request POST 'localhost:8080/hello' --header 'Content-Type: application/json' --data-raw '{"id":1,"age":2}'
	r.POST("hello", func(c *gin.Context) {
		stu := student{}
		err := c.ShouldBind(&stu)
		if err != nil {
			fmt.Println("err:", err)
			return
		}
		fmt.Printf("get stu:%+v\n", stu) // get stu:{ID:1 Name: Age:2}
	})

	/* 获取请求某个key对应的value 绑定到结构体
	curl --location --request POST 'http://localhost:8080/hi' \
	--header 'content-type: application/json' \
	--data-raw '{
	    "user":{
	        "name":"lena",
	        "age":12
	    }
	}'
	*/
	r.POST("hi", func(c *gin.Context) {
		data, err := c.GetRawData()
		if err != nil {
			panic(err)
		}
		type user struct {
			Name string `json:"name"`
			Age  int    `json:"age"`
		}
		type rsp struct {
			U user `json:"user"`
		}
		r := rsp{}
		err = json.Unmarshal(data, &r)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%+v\n", r)
	})
}
